package com.example.myapplication01.chapter05;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication01.R;
import com.example.myapplication01.chapter06.database.LoginDBHelper;
import com.example.myapplication01.chapter06.enity.LoginInfo;
import com.example.myapplication01.util.ViewUtil;

import java.util.Random;

public class LoginMainActivity extends AppCompatActivity implements View.OnClickListener,RadioGroup.OnCheckedChangeListener,View.OnFocusChangeListener{
    TextView tv_password;
    EditText et_password;
    CheckBox ck_remember;
    Button btn_forget;
    Button btn_login;
    RadioButton rb_password;
    RadioButton rb_verifycode;
    EditText et_phone;
    private String mVerifyCode;
    //    正确的密码
    private String mPassword = "123456";
    private ActivityResultLauncher<Intent> register;
//本地数据保存
    private SharedPreferences preferences;
    private LoginDBHelper mHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_main);
        rb_verifycode=findViewById(R.id.rb_verifycode);
        RadioGroup rg_login = findViewById(R.id.rg_login);
        btn_forget = findViewById(R.id.btn_forget);
        tv_password = findViewById(R.id.tv_password);
        et_password = findViewById(R.id.et_password);
        ck_remember = findViewById(R.id.ck_remember);
        rb_password=findViewById(R.id.rb_password);
        et_phone = findViewById(R.id.et_phone);//电话号码输入框
        et_phone.addTextChangedListener(new HideTextWatcher(et_phone, 11));
        et_password.addTextChangedListener(new HideTextWatcher(et_password, 6));
//        按钮点击事件监听
        btn_forget.setOnClickListener(this);
//        登录按钮
        btn_login=findViewById(R.id.btn_login);
        btn_login.setOnClickListener(this);
        rg_login.setOnCheckedChangeListener(this);

//          获取忘记密码页面中修改的新密码
        register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                Intent intent = result.getData();
                if (intent != null && result.getResultCode() == Activity.RESULT_OK) {
                    // 用户密码已改为新密码，故更新密码变量
                    mPassword = intent.getStringExtra("new_password");
                }
            }
        });
        et_password.setOnFocusChangeListener(this);

        preferences = getSharedPreferences("config", Context.MODE_PRIVATE);
        reload();
    }


    @Override
    protected void onStart() {
        super.onStart();
        mHelper = LoginDBHelper.getInstance(this);
        mHelper.openReadLink();
        mHelper.openWriteLink();

        reload();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mHelper.closeLink();
    }
    private void reload() {
        LoginInfo info = mHelper.queryTop();
        if (info != null && info.remember) {
            et_phone.setText(info.phone);
            et_password.setText(info.password);
            ck_remember.setChecked(true);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
//        验证码登录
        if(checkedId==R.id.rb_verifycode){
            tv_password.setText("验证码");
            et_password.setHint("请输入验证码");
            btn_forget.setText("获取验证码");
//            不可见
            ck_remember.setVisibility(TextView.GONE);
        }
//        密码登录
        if (checkedId == R.id.rb_password) {
            tv_password.setText("登录密码");
            et_password.setHint("请输入密码");
            btn_forget.setText("忘记密码");
//            可见
            ck_remember.setVisibility(TextView.VISIBLE);
        }
    }

    @Override
    public void onClick(View v) {
        String phone = et_phone.getText().toString();
        if (phone.length() < 11) {
            Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return;
        }
//        手机号合法时，
//        需要验证，当前按钮的功能是忘记密码还是获取验证码
//         点击了忘记密码或是获取验证码这个按钮
        if (v.getId() == R.id.btn_forget) {
//            当前是密码登录
            if (rb_password.isChecked()) {
//              跳转到找回密码页面
                Intent intent = new Intent(this, LoginForgetActivity.class);
                intent.putExtra("phone", phone);
                // 跳转到意图指定的活动页面
                register.launch(intent);
            }
//            当前是验证码登录
            if (rb_verifycode.isChecked()) {
                // 生成六位随机数字的验证码
                mVerifyCode = String.format("%06d", new Random().nextInt(999999));
                // 以下弹出提醒对话框，提示用户记住六位验证码数字
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                // 设置对话框的标题文本
                builder.setTitle("验证码");
                // 设置对话框的内容文本
                builder.setMessage("手机号" + phone + ",本次验证码是" + mVerifyCode + ",请输入验证码");
                // 设置对话框的肯定按钮文本及其点击监听器
                builder.setPositiveButton("ok", null);
                // 根据建造器构建提醒对话框对象
                AlertDialog dialog = builder.create();
                // 显示提醒对话框
                dialog.show();
            }
        }
//        点击登录
        if (v.getId() == R.id.btn_login) {
//           密码登录时
            if (rb_password.isChecked()) {
                    if(!mPassword.equals(et_password.getText().toString())){
                        Toast.makeText(this,"密码不正确",Toast.LENGTH_SHORT).show();
                        return;
                    }
//                    否则就是登录成功，提示登录成功
                loginSuccess();
            }
//            验证码登录
            if (rb_verifycode.isChecked()) {
                Log.v("验证码：%s", mVerifyCode);
                Log.v("输入的验证码：%s", String.valueOf(et_password.getText()));
                if(!mVerifyCode.equals(String.valueOf(et_password.getText()))){
                    Toast.makeText(this,"验证码不正确",Toast.LENGTH_SHORT).show();
                    return;
                }
//                否则就是验证码登录成功，然后提示
                loginSuccess();
            }
        }
    }
//    登录成功
    public void loginSuccess() {
        String desc = String.format("您的手机号码是%s，恭喜你通过登录验证，点击“确定”按钮返回上个页面", et_phone.getText().toString());
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("登录成功");
        builder.setPositiveButton("确定返回", (dialog, which) -> {
//            接收当前活动
            finish();
        });
        builder.setNegativeButton("我再看看", null);
        AlertDialog dialog = builder.create();
        dialog.show();
        if (ck_remember.isChecked()) {
            // 保存到數據庫
            LoginInfo info = new LoginInfo();
            info.phone = et_phone.getText().toString();
            info.password = et_password.getText().toString();
            info.remember = ck_remember.isChecked();
            mHelper.save(info);
        }
    }

    // 当密码输入框获取焦点之后，根据输入的电话号码，查询出对应的密码，自动填入
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (v.getId() == R.id.et_password && hasFocus) {
            LoginInfo info = mHelper.queryByPhone(et_phone.getText().toString());
            // 如果根据电话号码，查询出了密码
            if (info != null) {
                et_password.setText(info.password);
                ck_remember.setChecked(info.remember);
            } else {
                // 没有查到，清空密码
                et_password.setText("");
                ck_remember.setChecked(false);
            }
        }
    }

    class HideTextWatcher implements TextWatcher {
        public long maxLen;
        // 声明一个编辑框对象
        private EditText mView;

        public HideTextWatcher(EditText mView, long maxLen) {
            this.maxLen = maxLen;
            this.mView = mView;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String str = s.toString();
            if (str.length() == maxLen) {
                // 隐藏输入法软键盘
                ViewUtil.hideOneInputMethod(LoginMainActivity.this, mView);
            }
        }
    }
}